package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.admin.entity.AdSensitive;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.IAdSensitiveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.SensitiveDto;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 敏感词信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-01-22
 */
@Service
public class AdSensitiveServiceImpl extends ServiceImpl<AdSensitiveMapper, AdSensitive> implements IAdSensitiveService {

    /**
     * 保存敏感信息实体类对象
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveSensitive(SensitiveDto dto) {
        try {
            //敏感词不存在,保存敏感词
            AdSensitive adSensitive1 = new AdSensitive();
            BeanUtils.copyProperties(dto, adSensitive1);
            this.save(adSensitive1);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (BeansException e) {
            e.printStackTrace();
            log.error("后台保存敏感词错误：{}" + e.getMessage());
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 更新敏感词实体信息
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateSensitive(SensitiveDto dto) {
        try {
            //根据敏感词更新
            LambdaUpdateWrapper<AdSensitive> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(AdSensitive::getSensitives, dto.getUpdateSensitives());
            updateWrapper.set(AdSensitive::getSensitives, dto.getSensitives());
            this.update(updateWrapper);
            return ResponseResult.okResult();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("后台更新敏感词实体信息错误：{}" + e.getMessage());
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 删除敏感词实体信息
     * @param dto
     * @return
     */
    @Override
    public ResponseResult deleteSensitive(SensitiveDto dto) {
        //查询当前敏感词对象在后台中是否存在
        LambdaQueryWrapper<AdSensitive> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdSensitive::getSensitives, dto.getSensitives());
        AdSensitive sensitive = this.getOne(queryWrapper);
        if (sensitive == null) {
            //当前敏感词不存在直接返回
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //敏感词存在。根据id删除
        this.removeById(sensitive.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
